package com.eesujie.xcs.service.impl;

import com.eesujie.xcs.common.UserContext;
import com.eesujie.xcs.entity.dto.NoteDTO;
import com.eesujie.xcs.entity.po.NoteImagePO;
import com.eesujie.xcs.entity.po.NotePO;
import com.eesujie.xcs.entity.vo.NoteVO;
import com.eesujie.xcs.mapper.NoteMapper;
import com.eesujie.xcs.service.NoteImageService;
import com.eesujie.xcs.service.NoteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eesujie.xcs.service.UserService;
import com.eesujie.xcs.util.PojoUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 笔记表 服务实现类
 * </p>
 *
 * @author eesujie
 * @since 2023-04-19
 */
@Service
public class NoteServiceImpl extends ServiceImpl<NoteMapper, NotePO> implements NoteService {
    @Resource
    private NoteImageService noteImageService;
    @Resource
    private UserService userService;
    @Override
    public List<NoteVO> getAllNotes() {
        var poList = list();
        return poList.stream().map(po -> {
            NoteVO noteVO = PojoUtils.parseVO(po);
            var author = userService.getById(po.getUserId());
            noteVO.setAuthorAvatar(author.getAvatar());
            noteVO.setAuthorNickname(author.getNickname());
            return noteVO;
        }).toList();
    }

    @Override
    @Transactional
    public void publishNote(NoteDTO noteDTO) {
        NotePO notePO = parsePO(noteDTO);
        save(notePO);

        Long noteId = notePO.getId();
        List<NoteImagePO> noteImagePOS = noteDTO.getImages().stream()
                .map(image -> NoteImagePO
                        .builder()
                        .noteId(noteId)
                        .image(image)
                        .build()
                ).toList();
        noteImageService.saveBatch(noteImagePOS);
    }

    public NotePO parsePO(NoteDTO noteDTO) {
        NotePO notePO = new NotePO();
        notePO.setTitle(noteDTO.getTitle());
        notePO.setDescription(noteDTO.getDescription());
        notePO.setCover(noteDTO.getImages().get(0));
        notePO.setUserId(UserContext.getUserId());
        return notePO;
    }
}
